package com.zt.controller;


import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zt.entity.Result;
import com.zt.pojo.Coupons;
import com.zt.service.CouponsService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/coupons")
public class CouponController {

    private static final String COUPONS_KEY = "coupons:";
    
    @Autowired
    private CouponsService couponService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    
    @GetMapping("/valid")
    public Result getValidCoupons(Long id) {

            List<Coupons> coupons = couponService.getValidCoupons(id);
            return Result.success("",coupons);

    }



    // 从redis 中获取优惠卷列表
    // 根据用户id查询

    @GetMapping("/getCoupons")
    @SneakyThrows
    public Result getCoupons(Long id){
        String couponsStr = redisTemplate.opsForValue().get(COUPONS_KEY + id);
        if (couponsStr == null){
            return Result.error("没有优惠券");
        }
        ObjectMapper mapper = new ObjectMapper();
        List<Coupons> coupons = mapper.readValue(couponsStr, new TypeReference<List<Coupons>>(){});

        return Result.success("获取成功", coupons);
    }



/*  此方法仅用于测试，因该在管理端发放优惠卷
    @PostMapping("/addCoupons")
    @SneakyThrows
    public Result addCoupons(Long userid, Integer couponid){
        Coupons coupons = couponService.getById(couponid);
        if (coupons == null){
            return Result.error("优惠券不存在");
        }

        ObjectMapper mapper = new ObjectMapper();
        List<Coupons> couponsList;

        // 获取现有的优惠券列表
        String existingCouponsStr = redisTemplate.opsForValue().get(COUPONS_KEY + userid);
        if (existingCouponsStr == null) {
            // 如果没有现有优惠券，创建新列表
            couponsList = new ArrayList<>();
        } else {
            // 如果有现有优惠券，反序列化为列表
            couponsList = mapper.readValue(existingCouponsStr, new TypeReference<List<Coupons>>(){});
        }

        // 添加新优惠券到列表
        couponsList.add(coupons);

        // 将更新后的列表存储到Redis
        redisTemplate.opsForValue().set(COUPONS_KEY + userid, mapper.writeValueAsString(couponsList));
        return Result.success("添加成功");
    }*/




}